package com.itlong.cloud.rabbitmq.consumer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.itlong.cloud.POJO.DTO.property.PropertySubscriberHanlerDTO;
import com.itlong.cloud.POJO.PO.CloudIntercomAccountInfoPO;
import com.itlong.cloud.POJO.PO.DeviceBusinessChangeLogPO;
import com.itlong.cloud.POJO.PO.TimeTaskDeadMessageQueuePO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.app.dao.IAppUserLykzAccountDao;
import com.itlong.cloud.app.service.IAppLykzCloudIntercomAccountService;
import com.itlong.cloud.constants.RabbitMQConstant;
import com.itlong.cloud.enumerate.SmartCommunityEnum;
import com.itlong.cloud.rabbitmq.config.MessageSender;
import com.itlong.cloud.utils.data.handler.SqlUtil;
import com.itlong.cloud.utils.encrypt.Md5EncryptUtil;
import com.itlong.cloud.utils.node.JsonUtil;
import com.itlong.cloud.utils.random.LogicIdUtil;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <desc>
 *      创建灵云快智云对讲用户账号队列消费者。
 * </desc>
 *
 * @createDate 2018/08/23
 */
@Component
public class CreateLykzCloudIntercomAccountConsumer {

    private static final Logger LOG = LoggerFactory.getLogger(CreateLykzCloudIntercomAccountConsumer.class);

    @Autowired
    IAppLykzCloudIntercomAccountService iAppLykzCloudIntercomAccountService;

    //消息队列
    @Autowired
    private MessageSender messageSender;

    @Autowired
    private IAppUserLykzAccountDao iAppUserLykzAccountDao;

    /**
     * <desc>
     *      RabbitMQ_接收app用户id创建灵云快智云对讲用户账号
     * <desc/>
     *
     * @param   message 消息数据
     * @author Juguang.S
     * @createDate 2018/08/23
     */
    @RabbitListener(queues = RabbitMQConstant.RABBITMQ_CREATE_LYKZ_CLOUD_INTERCOM_ACCOUNT_QUEUE)
    public void process(Message message, Channel channel) throws IOException {
        byte[] body = message.getBody();
        //LOG.info("RabbitMQ_接收app用户id创建灵云快智云对讲用户账号:" + new String(body));
        try {
            List<DeviceBusinessChangeLogPO> deviceBusinessChangeLogPOS  = new ArrayList<>();
            Set<String> projectIdSet = new HashSet<>();
            TimeTaskDeadMessageQueuePO po= JsonUtil.toObject(new String(body), TimeTaskDeadMessageQueuePO.class);
            //List<Map<String,String>> map=JsonUtil.toObject(po.getMessageContent(), List.class);
            JSONObject dataJs = JSON.parseObject(po.getMessageContent());
            Object datas = dataJs.get("data");
            List<Map> list = JSONArray.parseArray(datas.toString(),Map.class);
            //JSONObject dataContent = dataJs.getJSONObject("data");
            for(Map<String,String> mapParams : list){
                String userId = mapParams.get("userId");
                String phoneNum = mapParams.get("phoneNum");
                String projectId = mapParams.get("projectId");
                String sipAccount = mapParams.get("sipAccount");
                projectIdSet.add(projectId);
                String sipPsd = Md5EncryptUtil.md5(userId + phoneNum).toLowerCase();
                //针对开启云对讲并且通过审核的userId查询是否已创建灵云快智的账号，如有则跳过
                Integer count = iAppLykzCloudIntercomAccountService.getUserInfoByUserId(userId);
                //String regex = "^((1[3,5,8][0-9])|(14[5,7])|(17[0,6,7,8])|(19[7]))\\d{8}$";
                String regex = "^1[3|4|5|6|7|8|9]\\d{9}$";
                Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
                Matcher m = p.matcher(phoneNum);
                if(!m.matches()){
                    continue;
                }

                Map<String,String> resultMap = iAppLykzCloudIntercomAccountService.getLykzCloudIntercomAccountByMoblie(phoneNum,"");

                if(resultMap==null){
                    CloudIntercomAccountInfoPO infoPO = iAppLykzCloudIntercomAccountService.createLykzCloudIntercomAccount(userId,phoneNum,"","");
                    //并将灵云快智的uerId做为sip账号保存至app-user-project表中
                    if(infoPO!=null){

                        //删除原SIP相关信息,并添加/更新SIP信息
                        PropertySubscriberHanlerDTO subscriberHanlerDTO = new PropertySubscriberHanlerDTO(projectId,infoPO.getClientUserId(), sipPsd, sipAccount);
                        JSONObject js = new JSONObject();
                        js.put("data",JSONObject.toJSON(subscriberHanlerDTO));
                        messageSender.send(RabbitMQConstant.RABBITMQ_SAVE_OR_UPDATE_SIP_QUEUE, JsonUtil.toJSON(js), RabbitMQConstant.RABBITMQ_EQUIP_EXCHANGE,
                                RabbitMQConstant.RABBITMQ_SAVE_OR_UPDATE_SIP_KEY);

                        iAppLykzCloudIntercomAccountService.updateUserSipAccount(infoPO.getClientUserId(),userId,sipPsd);
                    }
                }else{
                    //如果该用户已经绑定灵云账号 ，则从灵云获取绑定信息并进行保存处理
                    //首先根据手机号查询cloud_intercom_account_info表中是否已有该用户灵云信息数据 没有则保存
                    if(iAppLykzCloudIntercomAccountService.getExistLykzInfo(resultMap.get("lykzUserId"))==0){
                        CloudIntercomAccountInfoPO  infoPO = new CloudIntercomAccountInfoPO();
                        String lykzId = LogicIdUtil.bussinessId();
                        infoPO.setCloudIntercomAccountId(lykzId);
                        infoPO.setAccountType(1);
                        infoPO.setAccount(resultMap.get("clientNumber"));
                        infoPO.setToken(resultMap.get("loginToken"));
                        infoPO.setClientPwd(resultMap.get("clientPwd"));
                        infoPO.setClientUserId(resultMap.get("lykzUserId"));
                        infoPO.setStatus(1);
                        infoPO.setCreateTime(new Date());
                        Integer result = iAppUserLykzAccountDao.save(SqlUtil.durableData(infoPO, PlatformConstants.TABLE_SAVE));
                        if(result>0){
                            iAppUserLykzAccountDao.updateAppUserInfo(userId,lykzId);
                        }

                        //删除原SIP相关信息,并添加/更新SIP信息
                        PropertySubscriberHanlerDTO subscriberHanlerDTO = new PropertySubscriberHanlerDTO(projectId,infoPO.getClientUserId(), sipPsd, sipAccount);
                        JSONObject js = new JSONObject();
                        js.put("data",JSONObject.toJSON(subscriberHanlerDTO));
                        messageSender.send(RabbitMQConstant.RABBITMQ_SAVE_OR_UPDATE_SIP_QUEUE, JsonUtil.toJSON(js), RabbitMQConstant.RABBITMQ_EQUIP_EXCHANGE,
                                RabbitMQConstant.RABBITMQ_SAVE_OR_UPDATE_SIP_KEY);
                    }
                    iAppLykzCloudIntercomAccountService.updateUserSipAccount(resultMap.get("lykzUserId"),userId,sipPsd);
                }
            }
            //推送云对讲指令 向所有的设备推房间全量更新
            //List<String> projectList = iAppLykzCloudIntercomAccountService.getProjectid();
            for(String projectId : projectIdSet){
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("projectId",projectId);
                DeviceBusinessChangeLogPO deviceBusinessChangeLogPO
                        = new DeviceBusinessChangeLogPO(SmartCommunityEnum.PUSH_RELOGIN,jsonObject,projectId);
                deviceBusinessChangeLogPOS.add(deviceBusinessChangeLogPO);
            }

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("data",deviceBusinessChangeLogPOS);

            //云对讲业务指令
            messageSender.send(RabbitMQConstant.RABBITMQ_HANDLE_SMART_COMMUNITY_ORDERS_QUEUE,
                    JsonUtil.toJSON(jsonObject), RabbitMQConstant.RABBITMQ_SMART_COMMUNITY_ORDERS_EXCHANGE,
                    RabbitMQConstant.RABBITMQ_SMART_COMMUNITY_ORDERS_ROUTING_KEY);

        } catch (Exception e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
            LOG.error("【RabbitMQ_接收app用户id创建灵云快智云对讲用户账号】:处理异常", e);
        }finally {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
    }

}
